package cn.donting.web.desktop.sys.service;

import cn.donting.web.desktop.core.dao.UserRepository;
import cn.donting.web.desktop.core.exception.AppException;
import cn.donting.web.desktop.core.entity.User;
import cn.donting.web.desktop.top.user.UserSpaceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.Date;
import java.util.HashMap;

/**
 * @author donting
 * 2021-06-06 下午8:45
 */
@Service
@Slf4j
@WebListener
public class UserCenter implements HttpSessionListener,cn.donting.web.desktop.core.app.interfaces.UserCenter{
    @Autowired
    UserRepository userRepository;
    @Autowired
    HttpSession session;


    /**
     * 登录的用户集
     * <></>
     */
    private final HashMap<String, User> loginUsers = new HashMap<>();


    public User creatUser(String name, String password) throws AppException {
        User user = userRepository.findByName(name);
        if (user != null) {
            throw new AppException(name + " 该用户已被创建");
        }
        user = new User();
        user.setName(name);
        user.setPassword(password);
        user.setCreatTime(new Date());
        User save = userRepository.save(user);
        save.setPassword(null);
        return save;
    }

    /**
     * @param name
     * @param password
     * @return null 登录失败
     */
    public User login(String name, String password) {
        User user = userRepository.findByNameAndPassword(name, password);
        if (user != null) {
            user.setPassword(null);
            loginUsers.put(session.getId(), user);
            UserSpaceService.setLoginUserName(session.getId(), user.getName(),user.getId());
        } else {
            log.info("登录失败：" + name);
        }
        return user;
    }

    @Override
    public User getLoginUser() {
        return loginUsers.get(session.getId());
    }

    public User getLoginUser(String sessionId) {
        return loginUsers.get(sessionId);
    }

    public User logout() {
        UserSpaceService.removeLoginUserName(session.getId());
        return loginUsers.remove(session.getId());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        String id = se.getSession().getId();
        User remove = loginUsers.remove(id);
        UserSpaceService.removeLoginUserName(session.getId());
        if (remove != null) {
            log.info("超时登出user：" + remove.getName());
        }
    }
}
